<template>
    <div class="container">
        <a-form ref="loginForm" :model="search" autocomplete="off" @keyup.enter="handleSearch()">
            <iSearch>
                <template #FormData>
                    <a-form-item>
                        <iInput v-model:value="search.title" tip="文章标题" placeholder="请输入文章标题"></iInput>
                    </a-form-item>
                    <a-form-item>
                        <iSelect v-model:value="search.group_id" :option="ArticleGroup" index="id" label="group_name" tip="文章分组"></iSelect>
                    </a-form-item>
                    <a-form-item>
                        <a-checkbox-group v-model:value="search.state">
                            <a-checkbox v-for="(item,index) in DbArticleState" :key="index" :value="item.value">{{ item.label }}</a-checkbox>
                        </a-checkbox-group>
                    </a-form-item>
                </template>
                <template #Button>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                    <a-button @click="handleReset">重置</a-button>
                    <a-button type="primary" danger v-iscan="['cms:article:add']" @click="handleAdd">添加</a-button>
                </template>
            </iSearch>
        </a-form>
        <iTable @search="handlePagination" :total="total" :columns="columns" :tableData="tableData" :loading="loading">
            <template #group_name="{ record }">
                <span :style="record.group_state == 1 ? 'color: #000000;':'color: rgba(0, 0, 0, 0.45);'">
                    {{ record.group_name }}
                </span>
            </template>
            <template #title="{ record }">
                <div>
                    {{ record.title }}<a-tag v-if="record.top" size="small" style="margin-left: 5px;" color="red">置顶</a-tag>
                </div>
                <div>
                    <a :href="BaseHost(`${record.preview}${record.url_suffix}`)" target="_blank" style="font-size: 12px;color: rgba(0, 0, 0, 0.45);text-decoration: underline;">{{ BaseHost(`${record.preview}${record.url_suffix}`) }}</a>
                </div>
            </template>
            <template #state="{ record }">
                <a-tag :color="FuncDbArticleState(record.state || 0).color">{{ FuncDbArticleState(record.state || 0).label }}</a-tag>
            </template>
            <template #operate="{ record }">
                <a-flex gap="small" horizontal>
                    <a-button type="link" v-iscan="['cms:article:edit']" @click="handleEdit(record.id)">编辑</a-button>
                    <iDelete :auth="['cms:article:del','disabled']" @delete="handleDelete(record.id)"></iDelete>
                </a-flex>
            </template>
        </iTable>
        
        <a-drawer :title="(formState.id || 0) > 0 ? '编辑文章': '添加文章'" rootClassName="full-modal-drawer" width="40%" :open="EditVisible" @close="handleEditClose()" :loading="EditLoading">
            <a-form ref="formStateRef" :model="formState" autocomplete="off" :rules="formStateRule" layout="vertical">
                <a-flex wrap="wrap" gap="small">
                    <div>
                        <a-form-item name="group_id" label="分组">
                            <a-select v-model:value="formState.group_id" placeholder="请选择文章分组">
                                <a-select-option v-for="item in ArticleGroup" :value="item.id">{{ item.group_name }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item name="title" label="文章标题">
                            <a-input v-model:value="formState.title" placeholder="请输入文章标题"></a-input>
                        </a-form-item>
                        <a-form-item name="url_suffix">
                            <template #label>
                                URL键<a v-if="(formState.id || 0) > 0" :href="BaseHost(`${formState.preview}${formState.url_suffix}`)" style="font-size: 12px;margin-left: 10px">{{ BaseHost(`${formState.preview}${formState.url_suffix}`) }}</a>
                            </template>
                            <a-input v-model:value="formState.url_suffix" placeholder="请输入URL键"></a-input>
                        </a-form-item>
                        <a-form-item name="content" label="内容">
                            <iEditor v-model:value="formState.content" />
                        </a-form-item>
                        <a-form-item name="release_time" label="发布时间">
                            <iDatePick :value="formState.release_time" @change="handleReleaseTime" />
                        </a-form-item>
                        <a-flex>
                            <a-form-item name="state" label="状态">
                                <a-radio-group v-model:value="formState.state">
                                    <a-radio v-for="(item,index) in DbArticleState" :key="index" :value="item.value">{{ item.label }}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item name="state" label="置顶">
                                <a-radio-group v-model:value="formState.top">
                                    <a-radio v-for="(item,index) in DbArticleTopUp" :key="index" :value="item.value">{{ item.label }}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                        </a-flex>
                    </div>
                    <a-divider orientation="left">SEO</a-divider>
                    <div style="width: 100%;">
                        <a-form-item name="keywords" label="关键字">
                            <a-input v-model:value="formState.keywords" placeholder="请输入关键字"></a-input>
                        </a-form-item>
                        <a-form-item name="describe" label="描述">
                            <a-textarea v-model:value="formState.describe" placeholder="请输入描述"></a-textarea>
                        </a-form-item>
                    </div>
                </a-flex>
            </a-form>
            <template #extra>
                <a-space>
                    <a-button @click="handleEditClose()">取消</a-button>
                    <a-button type="primary" @click="handleSubmit()">保存</a-button>
                </a-space>
            </template>
        </a-drawer>
    </div>
</template>


<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { iPb } from '@/protobuf/interface/index'
import { ListArticle, ReadArticle, CreateArticle, UpdateArticle, DeleteArticle } from '@/api/article';
import { ListArticleGroup } from '@/api/article_group';
import { DbArticleState, DbArticleTopUp, FuncDbArticleState } from '@/tool/const'
import { FormInstance } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { Message } from '@/tool/antdv';
import { TableWidth } from '@/tool/enum'
import { BaseHost } from '@/tool/function'
import { Dayjs } from 'dayjs';
import { $DateTimeStamp } from '@/tool/function';

const formStateRef = ref<FormInstance>()
const formState = ref<iPb.IDbArticle>(iPb.DbArticle.create())
const formStateRule = reactive({
    group_id: [
        { required: true, message: '请选择文章分组' }
    ],
    title: [
        { required: true, message: '请输入文章标题' },
    ],
    url_suffix: [
        { required: true, message: '请输入URL键' }
    ],
    content: [
        { required: true, message: '请输入文章内容' }
    ],
})
const search = ref<iPb.Admin.IListArticleRequest>(iPb.Admin.ListArticleRequest.create())
const loading = ref<Boolean>(false)
const EditVisible = ref<Boolean>(false)
const EditLoading = ref<Boolean>(false)

const tableData = ref<Array<iPb.IDbArticle>>([])
const total = ref<number>(0)
const ArticleGroup = ref<Array<iPb.IDbArticleGroup>>([])

const handleAdd = () => {
    formStateRef.value?.resetFields()
    formState.value = iPb.DbArticle.create()
    formState.value.group_id = undefined
    formState.value.release_time = $DateTimeStamp()
    EditVisible.value = true
}
const handleEditClose = () => {
    EditVisible.value = false
}

const handleDelete = (id: number) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    DeleteArticle(iPb.Admin.DeleteArticleRequest.create({
        id: id
    })).then((_result: iPb.Admin.IDeleteArticleResponse) => {
        EditLoading.value = false
        Message.success({
            content: "删除成功",
        })
        initList()
    })
}

const handleReleaseTime = (e: Dayjs) => {
    formState.value.release_time = e
}

const handleEdit = (id: number) => {
    formStateRef.value?.resetFields()
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const ReadArticleRequest = iPb.Admin.ReadArticleRequest.create({
        id: id
    })
    ReadArticle(ReadArticleRequest).then((result:iPb.IDbArticle) => {
        formState.value = iPb.DbArticle.create(result)
        EditVisible.value = true
        EditLoading.value = false
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSubmit = () => {
    const formData = formState.value
    formStateRef.value?.validate().then(() => {
        if(EditLoading.value) {
            return
        }
        EditLoading.value = true
        if((formData.id || 0) > 0) {
            UpdateArticle(formData).then((_result:iPb.Admin.IUpdateArticleResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "保存成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }else {
            CreateArticle(formData).then((_result:iPb.Admin.ICreateArticleResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "添加成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }
    })
}

const handleReset = () => {
    search.value = iPb.Admin.ListAdminRequest.create()
    search.value.group_id = 0
    initList()
}

const handleSearch = () => {
    initList()
}

const handlePagination = (e: { current: number | undefined; pageSize: number | undefined; }) => {
    initList(e.current, e.pageSize)
}

const initList = (page = 1, limit = 15) => {
    if(loading.value) {
        return
    }
    loading.value = true
    search.value.limit = limit
    search.value.page = page
    ListArticle(iPb.Admin.ListArticleRequest.create(search.value)).then((result:iPb.Admin.IListArticleResponse) => {
        let R = iPb.Admin.ListArticleResponse.create(result)
        tableData.value = R.data
        total.value = R.count
        loading.value = false
    })
}

const initListArticleGroup = () => {
    ListArticleGroup(iPb.Admin.ListArticleGroupRequest.create()).then((result:iPb.Admin.IListArticleGroupResponse) => {
        let R = iPb.Admin.ListArticleGroupResponse.create(result)

        ArticleGroup.value = R.data
    })
}

const columns:TableColumnsType = [
    {
        title: "ID",
        dataIndex: "id",
        width: TableWidth.Id,
    },
    {
        title: "文章分组",
        dataIndex: "group_name",
        width: TableWidth.Group,
    },
    {
        title: "文章标题",
        dataIndex: "title",
        width: TableWidth.Info,
    },
    {
        title: "状态",
        dataIndex: "state",
        width: TableWidth.State,
    },
    {
        title: "发布时间",
        dataIndex: "release_time",
        key: "time",
        width: TableWidth.Time,
    },
    {
        title: "操作",
        dataIndex: "operate",
        width: TableWidth.Operate,
    }
]

onMounted(() => {
    initList()
    initListArticleGroup()
})

</script>


<style lang="less">
.third-layer {
    .ant-tree-list-holder-inner {
        display: inline-block !important;
    }
}
.last-layer {
    display: inline-flex !important;
}
</style>
